import os
import sys
sys.path.append(os.path.realpath(__file__)[0])

parentClass = object
currentDir = os.path.split(os.path.realpath(__file__))[0] + '/'
if os.path.exists(currentDir + "ParamsUtilsEntity.py") or os.path.exists(currentDir + "ParamsUtilsEntity.pyc"):
    try:
        ParamsUtilsEntity = object
        exec('from .ParamsUtilsEntity import ParamsUtilsEntity')
        parentClass = ParamsUtilsEntity
    except Exception as e:
        print(f'\033[0;31mimportError: {e}\033[0m')


class ParamsUtils(parentClass):
    def __init__(self, statement=True):
        super(ParamsUtils, self).__init__()
        if os.path.exists(currentDir + f'{self.__class__.__name__}Json'):
            data = {}
            with open(currentDir + f'./{self.__class__.__name__}Json', 'r', encoding='utf8') as fp:
                try:
                    data = eval(fp.read())
                except Exception as e:
                    self.printError(e)
            for key in data:
                value = data[key]
                exec(f'self.{key}="""{value}"""')
        if statement: self.statement()

    def get(self, key):
        value = None
        try:
            if hasattr(self, key):
                value = eval(f'self.{key}')
                if type(value) == list:
                    value = value[0]
        except Exception as e:
            self.printError(e)
        finally:
            return value

    def gets(self, key):
        value = None
        try:
            if hasattr(self, key):
                value = eval(f'self.{key}')
                if type(value) != list:
                    value = [value]
        except Exception as e:
            self.printError(e)
        finally:
            return value

    def set(self, key, value, replace=True):
        try:
            if not hasattr(self, key) or replace==True: exec(f'self.{key}="{value}"')
        except Exception as e:
            self.printError(e)

    def put(self, key, value):
        try:
            if hasattr(self, key):
                if type(eval(f"self.{key}")) == list:
                    exec(f'self.{key}.append("{value}")')
                else:
                    exec(f'self.{key}=[eval(f"self.{key}"), "{value}"]')
            else:
                exec(f'self.{key}=["{value}"]')
        except Exception as e:
            self.printError(e)

    def printError(self, e):
        print(f'\033[0;31m{self.__class__.__name__}Error: {e}\033[0m')
        errorLogPath = currentDir + f'{self.__class__.__name__}ErrorLog.log'
        if not os.path.exists(errorLogPath):
            os.mknod(errorLogPath)
        with open(errorLogPath, 'a+') as fp:
            fp.write(f"{e}\n")

    def statement(self):
        statement = f'{self.__class__.__name__}\n' \
                    '作者: 梦辰雪（Cui Mengchao）\n' \
                    '版本号: v1.0.0\n' \
                    '更新时间: 2023-05-10\n' \
                    'gitee: https://gitee.com/mcxgitee\n'
        print(f'\033[1;33m{statement}\033[0m\n')

# region 单例
instance = None

def initInstance(statement=True):
    global instance
    if not instance:
        instance = ParamsUtils(statement=statement)
    return instance
# endregion